import { createRouter, createWebHashHistory } from 'vue-router'

import store from "@/store";

// 路由懒加载:
const Layout = () => import('@/views/Layout.vue')
const Home = () => import('@/views/Home/index.vue')
const Category = () => import('@/views/category/index.vue')
const Search = () => import('@/views/search/index.vue')
const Goods = () => import('@/views/goods/index.vue')
const Login = () => import("@/views/login/index") 
const Cart = () => import('@/views/cart/index.vue')
const Checkout = () => import('@/views/checkout/index.vue')
const Pay = () => import('@/views/pay/index.vue')
const PayResult = () => import('@/views/pay/result.vue')

// 1. 定义路由规则: 什么路径显示什么组件
const routes = [
  {
    path:'/',
    component:Layout,
    children:[
      { path:'/', component:Home },
      { path:'/category/:id', component:Category },
      { path:'/search', component:Search },
      { path: "/product/:id", component: Goods },
      { path: "/cart", component: Cart },
      { path: '/user/checkout', component: Checkout },
      { path: '/user/pay', component: Pay },
      { path: '/user/pay/result', component: PayResult },
    ]
  },
  { path: "/login", component: Login },
]

// 2. createRouter函数是router实例的
const router = createRouter({
  // history 配置路由模式: hash(localhost:8080/#/home)  history(localhost:8080/home)
  // createWebHashHistory() 创建hash模式的路由
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 前进后退的时候，回到页面原理滚动的位置（还原浏览器原生效果）
    if (savedPosition) {
      return savedPosition
    } else {
      // 没有浏览过的到页面顶部
      return { top: 0 }
    }
  },
})

// 访问权限控制
router.beforeEach((to,from,next) => {
  const { profile } = store.state.user
  // 拦截登录（想去的地址是以/user开头&&未登录）
  if (to.path.startsWith('/user') && !profile.token) {
    // 把你想去的地址传递给登录页面，登录完成根据这个地址进行跳转
    // to.fullPath （包含地址栏的参数） /user/order?page=2
    return next({path:'login',query: {redirectUrl: to.fullPath}})
  }
  next()
})

export default router
